﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace Oridea.Data.Fetching.Example {
	class Program {
		private const int RowsInPage = 5;

		static void Main(string[] args) {
			// To simplify the example, direct repository construction is used instead of an IoC.
			var repository = new CustomerRepository();

			Console.Write("Please enter 'c' for CollectionFetcher interactive program or \r\n'd' for " +
				"DictionaryFetcher interactive program: ");
			string s = Console.ReadLine();
			switch(s) {
				case "c":
					TestCollection(repository);
					break;
				case "d":
					TestDictionary(repository);
					break;
				default:
					Console.WriteLine("Unknown option has been entered. Please run the program again.");
					break;
			}

			Console.WriteLine();
			Console.WriteLine("Thank you for evaluating Oridea.Data.Fetching!");
		}

		private static void TestDictionary(CustomerRepository repository) {
			Console.WriteLine("Constructing query for dictionary...");
			IFetcher<Dictionary<int, string>> nameByIdFetcher = repository.GetNameByIdDictionary();
			Console.WriteLine("Executing count query at the database...");
			Console.WriteLine("There are {0} entries in dictionary.", nameByIdFetcher.Count());
			Console.WriteLine("Fetching data from the database...");
			Dictionary<int, string> nameById = nameByIdFetcher.Fetch();

			string idString = String.Empty;
			do {
				Console.Write("Enter id of customer to show their name: ");
				idString = Console.ReadLine();
				int id;
				if (Int32.TryParse(idString, out id)) {
					string customerName;
					if (nameById.TryGetValue(id, out customerName)) {
						Console.WriteLine("Name of customer #{0}: {1}.", id, customerName);
					}
					else {
						Console.WriteLine("Could not found customer #{0}.", id);
					}
				} 
				else {
					Console.WriteLine("Incorrect id has been specified.");
				}
				Console.WriteLine();
			} while (!String.IsNullOrWhiteSpace(idString));
		}

		private static void TestCollection(CustomerRepository repository) {
			Console.WriteLine("\r\nEnter name of the customer to search for. Type empty string to exit.\r\n");
			Console.WriteLine("Customers are ordered by first name, last name, and then by id.");
			Console.Write("Filter: ");

			string filter = String.Empty;
			while (!String.IsNullOrWhiteSpace(filter = Console.ReadLine())) {
				Console.WriteLine("Constructing query with name containing '{0}'...", filter);
				IPagingFetcher<Customer> customerFetcher = repository.GetByName(filter).
					OrderBy(CustomerRepository.SorterByNameAndId);
			
				Console.WriteLine("Executing Count() -- only COUNT query will be executed on the database.");
				int count = customerFetcher.Count();
				Console.WriteLine("Found {0} customers.", count);

				if (count == 0) {
					Console.WriteLine("No customers found, fetch is cancelled.\r\n");
				}
				else if (count > RowsInPage) {
					Console.Write("\r\nMore than {0} customers found. Please type number of page to load (zero-based): ", RowsInPage);
					int pageToLoad;
					while (!Int32.TryParse(Console.ReadLine(), out pageToLoad)) {
						Console.Write("\r\nIncorrect integer, try again: ");
					}
					Console.WriteLine("Taking page #{0}...", pageToLoad);
					ReadOnlyCollection<Customer> onePage = customerFetcher.FetchPage(pageToLoad, RowsInPage);
					RenderCustomers(onePage);
				}
				else {
					Console.WriteLine("Executing Fetch() -- normal query will be executed at the database.\r\n");
					ReadOnlyCollection<Customer> fetchedCustomers = customerFetcher.Fetch();
					RenderCustomers(fetchedCustomers);
				}
				Console.Write("Filter: ");
			}
		}

		private static void RenderCustomers(ReadOnlyCollection<Customer> fetchedCustomers) {
			foreach (Customer c in fetchedCustomers) {
				Console.WriteLine("\tName: {0} {1}\r\n\tAddress: {2}\r\n\t# {3}\r\n",
					c.FirstName, c.LastName, c.Address, c.Id);
			}
		}

		///// The following is the programme used to generate Customers.xml as a sample data provider
		
		//private const string LoremIpsum =
		//    "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt Neque porro quisquam est qui dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem Ut enim ad minima veniam quis nostrum exercitationem ullam corporis suscipit laboriosam nisi ut aliquid ex ea commodi consequatur Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum";
		//private static readonly string[] Words = LoremIpsum.Split(' ').Select(w => Char.ToUpper(w[0]) + w.Substring(1)).ToArray();

		//[STAThread]
		//static void Main(string[] args) {
		//    Random r = new Random();
		//    StringBuilder xmlBuilder = new StringBuilder();
		//    for (int k = 1; k < 101; k++) {
		//        xmlBuilder.AppendFormat("\t<Customer id=\"{0}\" firstName=\"{1}\" lastName=\"{2}\" address=\"{3}\" />\r\n",
		//            k, getSomeWords(r, 1), getSomeWords(r, 1), getSomeWords(r, 10));
		//    }
		//    Clipboard.SetText(xmlBuilder.ToString());
		//}

		//static string getSomeWords(Random r, int maxCount) {
		//    StringBuilder wordsBuilder = new StringBuilder();
		//    int count = r.Next(1, maxCount);
		//    for(int i = 0; i < count; i++) {
		//        if (i > 0) {
		//            wordsBuilder.Append(' ');
		//        }
		//        int j = r.Next(0, Words.Length);
		//        wordsBuilder.Append(Words[j]);
		//    }
		//    return wordsBuilder.ToString();
		//}
	}
}
